package com.ruoyi.server.api.memberUserManagement.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.errorCode.CommonException;
import com.ruoyi.common.utils.BeanUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.validator.ValidatorUtil;
import com.ruoyi.server.api.coach.domain.CoachManagement;
import com.ruoyi.server.api.hourRecord.domain.HourRecord;
import com.ruoyi.server.api.hourRecord.mapper.HourRecordMapper;
import com.ruoyi.server.api.memberBindCardRecord.domain.MemberBindCardRecord;
import com.ruoyi.server.api.memberBindCardRecord.mapper.MemberBindCardRecordMapper;
import com.ruoyi.server.api.memberCardNumber.domain.MemberCardNumber;
import com.ruoyi.server.api.memberCoach.domain.MemberCoach;
import com.ruoyi.server.api.memberCoach.mapper.MemberCoachMapper;
import com.ruoyi.server.api.memberTypeManagement.domain.MemberTypeManagement;
import com.ruoyi.server.api.memberTypeManagement.mapper.MemberTypeManagementMapper;
import com.ruoyi.server.api.memberUserManagement.domain.MemberUserManagement;
import com.ruoyi.server.api.memberUserManagement.mapper.MemberUserManagementMapper;
import com.ruoyi.server.api.memberUserManagement.model.MemberUserAndBindCardModel;
import com.ruoyi.server.api.memberUserManagement.service.IMemberUserManagementService;
import com.ruoyi.server.api.membershipRelationships.mapper.MembershipRelationshipsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 会员用户Service业务层处理
 *
 * @author zmh
 * @date 2024-06-11
 */
@Service
public class MemberUserManagementServiceImpl implements IMemberUserManagementService {
    @Autowired
    private MemberUserManagementMapper memberUserManagementMapper;
    @Autowired
    private MemberBindCardRecordMapper memberBindCardRecordMapper;
    @Autowired
    private MembershipRelationshipsMapper membershipRelationshipsMapper;
    @Autowired
    private MemberTypeManagementMapper memberTypeManagementMapper;
    @Autowired
    private MemberCoachMapper memberCoachMapper;
    @Autowired
    private HourRecordMapper recordMapper;

    /**
     * 查询会员用户
     *
     * @param id 会员用户主键
     * @return 会员用户
     */
    @Override
    public MemberUserManagement selectMemberUserManagementById(Long id) {
        return memberUserManagementMapper.selectMemberUserManagementById(id);
    }

    /**
     * @param memberUserManagement
     * @Author ZMH
     * @Description 全查模糊查，普通会员和vip私教会员的会员用户信息
     * @Date 2024/6/11 11:02
     * @Return com.ruoyi.server.api.memberUserManagement.domain.MemberUserManagement
     */
    @Override
    public List<MemberUserManagement> selectMemberUserManagementList(MemberUserManagement memberUserManagement) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        memberUserManagement.setVenueUniqueIdentifier(loginUser.getUser().getVenueUniqueIdentifier());
        return memberUserManagementMapper.selectMemberUserManagementList(memberUserManagement);
    }

    /**
     * @param id venueUniqueIdentifier
     * @Author ZMH
     * @Description 根据id查询单个会员id
     * @Date 2024/6/11 11:02
     * @Return com.ruoyi.server.api.memberUserManagement.model.MemberUserAndTypeModel
     */
    @Override
    public MemberUserAndBindCardModel getById(Integer id, String venueUniqueIdentifier) {
        //在登录信息内获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //将用户信息里面的租户标识赋值
        venueUniqueIdentifier = loginUser.getUser().getVenueUniqueIdentifier();
        MemberUserAndBindCardModel byId = memberUserManagementMapper.getById(id, venueUniqueIdentifier);
        if (byId.getExpirationTime() == null) {
            return byId;
        } else {
            // 获取 rcreateTime 和 expirationTime 字段的 Date 对象
            Date rcreateTimeDate = byId.getRcreateTime();
            Date expirationTimeDate = byId.getExpirationTime();
            // 将 Date 对象转换为 LocalDate 对象
            LocalDate rcreateTime = rcreateTimeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate expirationTime = expirationTimeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            // 计算两个日期之间的差异
            Period period = Period.between(rcreateTime, expirationTime);
            int diffMonths = period.getYears() * 12 + period.getMonths();
            byId.setServiceLife(diffMonths);
            return byId;
        }
    }


    /**
     * @param memberUserAndBindCardModel
     * @Author ZMH
     * @Description 新增会员用户信息
     * @Date 2024/6/12 9:22
     * @Return
     */
    @Override
    public AjaxResult insertMemberUserManagement(MemberUserAndBindCardModel memberUserAndBindCardModel) throws CommonException {
        // 获取唯一标识
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String venueUniqueIdentifier = loginUser.getUser().getVenueUniqueIdentifier();
        // 校验参数
        if (ValidatorUtil.ValidationObject(memberUserAndBindCardModel)) {
            MemberUserManagement memberUserManagement1 = memberUserManagementMapper.selectPhone(memberUserAndBindCardModel.getMemberUserPhone(), venueUniqueIdentifier);
            if (StringUtils.isNotNull(memberUserManagement1)) {
                return AjaxResult.error("手机号已存在");
            } else {
                // 设置公共属性
                Date currentDate = new Date();
                memberUserAndBindCardModel.setVenueUniqueIdentifier(venueUniqueIdentifier);
                memberUserAndBindCardModel.setCreateTime(currentDate);
                memberUserAndBindCardModel.setUpdateTime(currentDate);
                // 创建会员用户表实体类对象并赋值
                MemberUserManagement memberUserManagement = new MemberUserManagement();
                BeanUtils.copy(memberUserAndBindCardModel, memberUserManagement);
                // 新增会员用户信息
                int insertMemberResult = memberUserManagementMapper.insertMemberUserManagement(memberUserManagement);
                // 获取会员类型管理信息
                MemberTypeManagement memberTypeManagement = memberTypeManagementMapper.selectByMemberType(
                        memberUserAndBindCardModel.getMemberType(), venueUniqueIdentifier);
                // 设置会员类型相关信息
                memberUserAndBindCardModel.setMemberTypeName(memberTypeManagement.getMemberTypeName());
                memberUserAndBindCardModel.setMemberTypeRemarks(memberTypeManagement.getMemberTypeRemarks());
                // 创建绑卡记录实体类对象并赋值
                MemberBindCardRecord memberBindCardRecord = new MemberBindCardRecord();
                BeanUtils.copy(memberUserAndBindCardModel, memberBindCardRecord);
                MemberTypeManagement memberTypeManagement1 = memberTypeManagementMapper.selectMemberTypeManagementById(memberBindCardRecord.getMemberType(), venueUniqueIdentifier);
                memberBindCardRecord.setMemberType(memberTypeManagement1.getMemberType());
                memberBindCardRecord.setMemberTypeName(memberTypeManagement1.getMemberTypeName());
                memberBindCardRecord.setTypeId(memberUserAndBindCardModel.getTypeId());
                // 新增会员绑卡记录信息
                int insertBindCardResult = memberBindCardRecordMapper.insertMemberBindCardRecord(memberBindCardRecord);
                if (insertMemberResult > 0 && insertBindCardResult > 0) {
                    // 获取新生成的ID并设置
                    memberUserAndBindCardModel.setBindId(memberBindCardRecord.getId());
                    memberUserAndBindCardModel.setMemberUserId(memberUserManagement.getId());
                    // 新增会员用户与会员卡关系表
                    membershipRelationshipsMapper.insertMembershipRelationships(memberUserAndBindCardModel);
                    //循环遍历，连续插入数据
                    List<MemberCoach> courseAndCoachList = memberUserAndBindCardModel.getCourseAndCoachData();
                    for (MemberCoach memberCoachList : courseAndCoachList) {
                        MemberCoach memberCoach = new MemberCoach();
                        //赋值
                        memberCoach.setCourseTime(memberCoachList.getCourseTime());
                        memberCoach.setMemberUserId(memberUserAndBindCardModel.getMemberUserId());
                        memberCoach.setCoachId(memberCoachList.getId());
                        memberCoach.setVenueUniqueIdentifier(memberUserAndBindCardModel.getVenueUniqueIdentifier());
                        memberCoach.setCreateTime(new Date());
                        memberCoach.setUpdateTime(new Date());
                        //将数据插入
                        memberCoachMapper.insertMemberCoach(memberCoach);
                    }
                    return AjaxResult.success("成功");
                } else {
                    return AjaxResult.error("遍历失败");
                }
            }
        }
        return AjaxResult.success("成功");
    }


    /**
     * 修改会员用户
     *
     * @param memberUserAndBindCardModel 会员用户
     * @return 结果
     */
    @Override
    public AjaxResult updateMemberUserManagement(MemberUserAndBindCardModel memberUserAndBindCardModel) {
        // 获取唯一标识
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String venueUniqueIdentifier = loginUser.getUser().getVenueUniqueIdentifier();
        String userName = loginUser.getUser().getUserName();
        //创建memberUserManagement实体类对象
        MemberUserManagement memberUserManagement = new MemberUserManagement();
        //将数据复制
        BeanUtils.copy(memberUserAndBindCardModel, memberUserManagement);
        //将修改的时间赋值为现在
        memberUserManagement.setUpdateTime(new Date());
        //调用mapper
        memberUserManagementMapper.updateMemberUserManagement(memberUserManagement);
        //根据id和唯一标识查询单个会员信息
        MemberUserAndBindCardModel byId = memberUserManagementMapper.getById(memberUserAndBindCardModel.getId(), venueUniqueIdentifier);
        //根据id和唯一标识查询类型卡
        MemberTypeManagement memberTypeManagement = memberTypeManagementMapper.selectByMemberType(
                memberUserAndBindCardModel.getMemberType(), venueUniqueIdentifier);        //创建memberBindCardRecord实体类对象
        MemberBindCardRecord memberBindCardRecord = new MemberBindCardRecord();
        //将数据复制
        BeanUtils.copy(memberUserAndBindCardModel, memberBindCardRecord);
        //将查询出来的Bindid赋值给绑卡及记录表id
        memberBindCardRecord.setId(byId.getBindId());
        memberBindCardRecord.setMemberType(memberTypeManagement.getMemberType());
        memberBindCardRecord.setMemberTypeName(memberTypeManagement.getMemberTypeName());
        memberBindCardRecord.setMemberTypeRemarks(memberTypeManagement.getMemberTypeRemarks());
        //调用mapper
        memberUserManagementMapper.updateMemberBindCardRecord(memberBindCardRecord);
        //循环遍历，连续插入数据
        List<MemberCoach> courseAndCoachList = memberUserAndBindCardModel.getCourseAndCoachData();
        for (MemberCoach memberCoachList : courseAndCoachList) {
            MemberCoach memberCoach = memberCoachMapper.selectMemberCoachById(memberCoachList.getCoachId(), memberCoachList.getMemberUserId(), venueUniqueIdentifier);
            //判断是否为空
            if (StringUtils.isNotNull(memberCoach)){
                //获得新课时
                Integer newCourseTime = memberCoachList.getCourseTime();
                if (StringUtils.isNotNull(newCourseTime)){
                    int i = memberCoachMapper.addCourseTime(newCourseTime, memberCoachList.getCoachId(), memberCoachList.getMemberUserId(), venueUniqueIdentifier);
                    //判断是否大于0
                    if (i > 0){
                        Integer oldCourseTime = memberCoach.getCourseTime();
                        //获得新课时与旧时时的差值
                        Integer middleCourseTime = newCourseTime - oldCourseTime;
                        HourRecord hourRecord = new HourRecord();
                        hourRecord.setVenueUniqueIdentifier(venueUniqueIdentifier);
                        hourRecord.setMemberUserId(memberCoachList.getMemberUserId());
                        hourRecord.setCoachId(memberCoachList.getCoachId());
                        hourRecord.setOperator(userName);
                        hourRecord.setStatus(0);
                        hourRecord.setStatusHour(middleCourseTime);
                        hourRecord.setCreateTime(new Date());
                        hourRecord.setUpdateTime(new Date());
                        recordMapper.insertHourRecord(hourRecord);
                    }
                }else {
                    return AjaxResult.error("课时记录为空");
                }
            }else {
                //创建实体类对象
                MemberCoach memberCoach1 = new MemberCoach();
                //获得新课时
                Integer newCourseTime = memberCoachList.getCourseTime();
                //赋值
                memberCoach1.setCourseTime(newCourseTime);
                memberCoach1.setMemberUserId(memberUserAndBindCardModel.getMemberUserId());
                memberCoach1.setCoachId(memberCoachList.getId());
                memberCoach1.setVenueUniqueIdentifier(memberUserAndBindCardModel.getVenueUniqueIdentifier());
                memberCoach1.setCreateTime(new Date());
                memberCoach1.setUpdateTime(new Date());
                //将数据插入
                memberCoachMapper.insertMemberCoach(memberCoach1);
            }
        }
        return AjaxResult.success("操作成功");
    }
    /**
     * 批量删除会员用户
     *
     * @param ids 需要删除的会员用户主键
     * @return 结果
     */
    @Override
    public int deleteMemberUserManagementByIds(Long[] ids) {
        return memberUserManagementMapper.deleteMemberUserManagementByIds(ids);
    }

    /**
     * 删除会员用户信息
     *
     * @param id 会员用户主键
     * @return 结果
     */
    @Override
    public int deleteMemberUserManagementById(Long id) {
        return memberUserManagementMapper.deleteMemberUserManagementById(id);
    }

    /**
    * @Author hjh
    * @Description 根据会员卡号查询用户信息
    * @Date 2024/6/13 8:30
    * @Return com.ruoyi.common.core.domain.AjaxResult
    * @param membershipCardNumber
    */
    @Override
    public AjaxResult selectUserInfoByNumid(String membershipCardNumber) {
        if (StringUtils.isNotEmpty(membershipCardNumber)) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String venueUniqueIdentifier = loginUser.getUser().getVenueUniqueIdentifier();
            if (StringUtils.isNotEmpty(venueUniqueIdentifier)) {
                {
                    MemberUserAndBindCardModel memberUserAndBindCardModel = memberUserManagementMapper.selectUserInfoByNumid(membershipCardNumber, venueUniqueIdentifier);
                    return AjaxResult.success(memberUserAndBindCardModel);
                }
            } else {
                return AjaxResult.error("未找到该会员卡所属的场馆");
            }
        } else {
            return AjaxResult.error("该会员卡没有绑定用户");
        }
    }

    /**
    * @Author hjh
    * @Description 查询当天入场人数
    * @Date 2024/6/13 10:01
    * @Return com.ruoyi.common.core.domain.AjaxResult
    * @param currentDate
    */
    @Override
    public AjaxResult selectEntranceNumber(String currentDate) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String venueUniqueIdentifier = loginUser.getUser().getVenueUniqueIdentifier();
        if (StringUtils.isNotEmpty(currentDate) && StringUtils.isNotEmpty(venueUniqueIdentifier)){
            List<MemberCardNumber> memberCardNumbers = memberUserManagementMapper.selectEntranceNumber(venueUniqueIdentifier, currentDate);
            int count = 0;
            if (memberCardNumbers.size() > 0){
                count = memberCardNumbers.size();
            }
            return AjaxResult.success(count);
        }else {
            return AjaxResult.error("查询异常");
        }
    }

    /**
     * @Author hjh
     * @Description 查看用户是否入场
     * @Date 2024/6/17 11:03
     * @Return com.ruoyi.common.core.domain.AjaxResult
     * @param membershipCardNumber
     */
    @Override
    public AjaxResult userIfEntrance(String membershipCardNumber) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(new Date());
            //获取当前用户所在场馆标识
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String venueUniqueIdentifier = loginUser.getUser().getVenueUniqueIdentifier();
            List<MemberCardNumber> memberCardNumberUser = memberUserManagementMapper.userIfEntrance(venueUniqueIdentifier,membershipCardNumber,formattedDate);
            //用户入场，更新刷卡时间
            if (memberCardNumberUser.size() > 0){
                MemberCardNumber memberCardNumber = new MemberCardNumber();
                memberCardNumber.setVenueUniqueIdentifier(venueUniqueIdentifier);
                memberCardNumber.setMembershipCardNumber(membershipCardNumber);
                int result = memberUserManagementMapper.userDepartureUpdate(memberCardNumber);
                return AjaxResult.success(result);
            } else {
                //未入场
                //查询用户会员卡类型
                MemberUserAndBindCardModel memberUserAndTypeModel = memberUserManagementMapper.selectUserMemberType(venueUniqueIdentifier, membershipCardNumber);
                //关联表ID
                Integer id = memberUserAndTypeModel.getMemberUserId();
                //绑卡记录ID
                Integer bindId = memberUserAndTypeModel.getBindId();
                //会员类型 （0次卡 1月卡 2年卡 3体验卡）
                Integer memberType = memberUserAndTypeModel.getMemberType();
                //可用次数
                Integer availableFrequency = memberUserAndTypeModel.getAvailableFrequency();
                //卡的天数
                Integer cardDays = memberUserAndTypeModel.getCardDays();
                if (memberType == 0){
                    if (availableFrequency > 0){
                        //次数 -1
                        memberUserManagementMapper.deleteByMemberUserPhone(venueUniqueIdentifier,bindId);
                        //添加用户刷卡记录
                        MemberCardNumber memberCardNumber = new MemberCardNumber();
                        memberCardNumber.setVenueUniqueIdentifier(venueUniqueIdentifier);
                        memberCardNumber.setMembershipCardNumber(membershipCardNumber);
                        int result = memberUserManagementMapper.userEntranceInsert(memberCardNumber);
                        return AjaxResult.success(result);
                    }else {
                        return AjaxResult.success("会员卡次数已用完");
                    }
                } else {
                    // 获取当前时间
                    long currentTime = System.currentTimeMillis();
                    // 将天数转换为毫秒数
                    long daysInMillis = cardDays * 24 * 60 * 60 * 1000;
                    // 计算过期时间
                    long expirationTime = currentTime + daysInMillis;

                    if (expirationTime < currentTime) {
                        return AjaxResult.success("会员卡已过期");
                    } else if (expirationTime == currentTime) {
                        return AjaxResult.success("会员卡已过期");
                    } else {
                        //添加用户刷卡记录
                        MemberCardNumber memberCardNumber = new MemberCardNumber();
                        memberCardNumber.setVenueUniqueIdentifier(venueUniqueIdentifier);
                        memberCardNumber.setMembershipCardNumber(membershipCardNumber);
                        int result = memberUserManagementMapper.userEntranceInsert(memberCardNumber);
                        return AjaxResult.success(result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("系统错误");
    }

    /**
    * @Author hjh
    * @Description 查询会员是否有私教
    * @Date 2024/6/16 20:51
    * @Return com.ruoyi.common.core.domain.AjaxResult
    * @param membershipCardNumber
    */
    @Override
    public AjaxResult selectIfPersonalTrainer(String membershipCardNumber) {
        String venueUniqueIdentifier = SecurityUtils.getLoginUser().getUser().getVenueUniqueIdentifier();
        if (StringUtils.isNotEmpty(membershipCardNumber) && StringUtils.isNotEmpty(venueUniqueIdentifier)){
            List<CoachManagement> coachManagements = memberUserManagementMapper.selectIfPersonalTrainer(venueUniqueIdentifier, membershipCardNumber);
            return AjaxResult.success(coachManagements);
        }else {
            return  AjaxResult.error("无会员信息");
        }
    }

    /**
    * @Author hjh
    * @Description 判断会员卡是否有会员
    * @Date 2024/6/17 14:21
    * @Return com.ruoyi.common.core.domain.AjaxResult
    * @param membershipCardNumber
    */
    @Override
    public AjaxResult ifMemberCardBind(String membershipCardNumber) {
        String venueUniqueIdentifier = SecurityUtils.getLoginUser().getUser().getVenueUniqueIdentifier();
        if (StringUtils.isNotEmpty(membershipCardNumber) && StringUtils.isNotEmpty(venueUniqueIdentifier)){
            int result = memberUserManagementMapper.ifMemberCardBind(membershipCardNumber, venueUniqueIdentifier);
            return AjaxResult.success(result);
        }else {
            return  AjaxResult.error("无会员卡信息");
        }
    }
}
